package com.example.springsecurity.security;


import com.sun.org.apache.xml.internal.security.algorithms.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
import java.util.*;
@Component
public class TokenManager {
    //token有效时长
    private long tokenEcpiration = 24*60*60*1000;
    //编码秘钥
    private String secret = "123456";
    //1 使用jwt根据用户名生成token
    public String createToken(String username) {
        long JWT_EXPIRED = 4 * 60 * 1000;
        try {
            // 设置过期时间
            Date date = new Date(System.currentTimeMillis() + JWT_EXPIRED );
            // 私钥和加密算法
            Algorithm algorithm = Algorithm.HMAC256(secret);
            // 设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("Type", "Jwt");
            header.put("alg", "HS256");
            // 返回token字符串
            return JWT.create()
                    .withHeader(header)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            return null;
        }
    }
    //2 根据token字符串得到用户信息
    public String getUserInfoFromToken(String token) {

        // 解析token
        Algorithm algorithm = Algorithm.HMAC256(secret);
        DecodedJWT decodedJWT = JWT.require(algorithm).build().verify(token);
        String subject = decodedJWT.getSubject();
        return subject;
    }
    //3 删除token
    public void removeToken(String token) { }
}
